package com.ws.gc.web.auth;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.ws.gc.mapper.user.entity.SysUser;
import com.ws.gc.mapper.user.mapper.SysRoleMapper;
import com.ws.gc.mapper.user.mapper.SysUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.core.Ordered;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.*;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.ArrayList;
import java.util.List;

@Component
public class CustomUserDetailsService implements ReactiveUserDetailsService, GlobalFilter, Ordered {
    private SysUserMapper userMapper;
    private SysRoleMapper roleMapper;
    private PasswordEncoder passwordEncoder;
    private String username;

    @Autowired
    public CustomUserDetailsService(SysUserMapper userMapper,
                                    SysRoleMapper roleMapper,
                                    PasswordEncoder passwordEncoder){
        this.userMapper = userMapper;
        this.roleMapper = roleMapper;
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    public Mono<UserDetails> findByUsername(String username) {
        // 通过用户名从数据库获取用户信息
        EntityWrapper<SysUser> ew = new EntityWrapper<>();
        ew.eq("username",username);
        List<SysUser> users = userMapper.selectList(ew);
        if (users.size()==0) {
            throw new UsernameNotFoundException("用户不存在");
        }

        // 得到用户角色
        long rid = users.get(0).getRoleId();
        if(rid == 0){
            throw new UsernameNotFoundException("角色信息不存在");
        }
        String role = roleMapper.selectById(rid).getName();
        this.username = username;
        // 角色集合
        List<GrantedAuthority> authorities = new ArrayList<>();
        // 角色必须以`ROLE_`开头，数据库中没有，则在这里加
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
        UserDetails user = User.withUsername(username).password(passwordEncoder.encode(users.get(0).getPassword())).authorities(authorities).build();
        return Mono.just(user);
    }

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //exchange.getSession().doOnNext(t->t.set)
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -100;
    }
}
